#! /usr/bin/env python
#coding=utf-8

import requests

#给requests打编码补丁
def monkey_patch():
	prop = requests.models.Response.content
	def content(self):
		_content = prop.fget(self)
		if self.encoding == 'ISO-8859-1':
			encodings = requests.utils.get_encodings_from_content(_content)
			if encodings:
				self.encoding = encodings[0]
			else:
				self.encoding = self.apparent_encoding
			_content = _content.decode(self.encoding, 'replace').encode('utf8', 'replace')
			self._content = _content
		return _content
	requests.models.Response.content = property(content)


monkey_patch()
class HttpService(object):
	"""docstring for HttpService"""
	def __init__(self):
		super(HttpService,self).__init__()
		self.headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"}
		self.session = requests.Session()
		self.timeout = 20

	def getSession(self):
		return  self.session

	def get(self,url,params=None,headers=None):
		params = params or {}
		headers =headers or  self.headers

		response = self.session.get(url=url,params=params,headers=headers,timeout=self.timeout)
		if response.status_code ==200:
			result =  response.text
			return result
		return False
		pass

	def post(self,url,params=None,headers=None):
		params = params or {}
		headers =headers or  self.headers

		response = self.session.post(url=url,params=params,headers=self.headers,timeout=self.timeout)
		if response.status_code ==200:
			result =  response.text
			return result
		return False
		pass

	def get_img_response(self,url,params={}):
		response = httpservice.getSession().get(url=url, params=params,stream=True,headers=self.headers)
		# logging.info(result)
		return response
		pass

	def get_input_value(self,html):
		# print(html)
		soup = BeautifulSoup(html, 'html.parser')
		allinput = soup.find_all('input')
		allinputs= {}
		for inputs in allinput:
			input_name=inputs.get("name")
			input_value=inputs.get("value")
			# print(input_name,input_value)
			if input_name and  input_value:
				allinputs[input_name] =input_value
		return allinputs
		pass

